package day4.homework;

import java.lang.reflect.Field;

//a.通过反射定义一个方法可以实现修改任意对象的属性值
//    通过反射定义一个方法可以实现获取任意对象的属性值
//    提示：设置属性  setProperty(对象，属性名,新的属性值)
//              获取属性  getProperty(对象，属性名)
public
class Demo3 {
    public static
    void main(String[] args) {
        Cat c = new Cat();
        System.out.println("修改前");
        System.out.println(getProperty(c,"name")+" "+getProperty(c,"age")+" "+getProperty(c,"type"));
        setProperty(c,"name","旺财");
        setProperty(c,"age",9);
        setProperty(c,"type","三花猫");
        System.out.println("修改后");
        System.out.println(getProperty(c,"name")+" "+getProperty(c,"age")+" "+getProperty(c,"type"));
    }
    public static Object getProperty(Object o,String name){
        Object value=null;
        try {
            Class c=o.getClass();
            Field f=c.getDeclaredField(name);
            f.setAccessible(true);
           value=f.get(o);
        } catch (NoSuchFieldException | IllegalAccessException|IllegalArgumentException e) {
            e.printStackTrace();
        }
        return value;
    }
    public static
    void setProperty(Object o, String name, Object num){
        try {
            Class c=o.getClass();
            Field f=c.getDeclaredField(name);
            f.setAccessible(true);
            f.set(o,num);
        } catch (NoSuchFieldException | IllegalAccessException |IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}
